package com.cmcc.aregister;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Application;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.AsyncTask;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.cmcc.aregister.cs.asntask.InterfaceUtils.Liuliang_tongji;
import com.cmcc.aregister.cs.asntask.MyAsynTaskOther;
import com.cmcc.aregister.cs.constant.Arguments;
import com.cmcc.aregister.cs.constant.ConfigUtilHelper;
import com.cmcc.aregister.cs.constant.GlobalSetting;
import com.cmcc.aregister.cs.database.DatabaseImpl;
import com.cmcc.aregister.cs.database.IDatabase;
import com.cmcc.aregister.cs.model.Hospital;
import com.cmcc.aregister.cs.model.UpdateEntity;
import com.cmcc.aregister.cs.util.ImageCache;
import com.cmcc.aregister.cs.util.Utils;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

/**
 * 
 * @author swq
 * 
 */
public class MyApplication extends Application implements Liuliang_tongji {

    private static final String TAG = "MyApplication";
    private static MyApplication sInstance = null;
    public UpdateEntity mUpdateEntity = new UpdateEntity();

    public Map<String, String> hospitalMap = new HashMap<String, String>();
    public Map<String, String> departmentMap = new HashMap<String, String>();
    public Map<String, String> doctorMap = new HashMap<String, String>();
    public boolean cancelAppFlag = false;
    public int area_type = -1;
    public int appPosition = -1;
    public boolean confirm_order_success = false;
    public static long startLiuliang = 0l;// 当前流量
    public void cancelApp(int area_type, int position) {
        this.area_type = area_type;
        cancelAppFlag = true;
        this.appPosition = position;
    }

    public boolean changeAttention = false;
    public int type = -1;
    public int position = -1;
    public String attentioin = "";

    public long stime, etime;

    public void changeAttention(int type, String id, int position, String attention) {
        this.type = type;
        changeAttention = true;
        this.position = position;
        this.attentioin = attention;
        if (type == 0) {
            hospitalMap.put(id, attention);
        }
        else if (type == 1) {
            departmentMap.put(id, attention);
        }
        else {
            doctorMap.put(id, attention);
        }
    }

    public void changeAttention(int type, String id, String attention) {
        // this.type = type;
        // changeAttention = true;
        // this.position = position;
        // this.attentioin = attention;
        if (type == 0) {
            hospitalMap.put(id, attention);
        }
        else if (type == 1) {
            departmentMap.put(id, attention);
        }
        else {
            doctorMap.put(id, attention);
        }
    }

    public boolean orderLocal = false;
    public boolean orderOther = false;

    /**
     * 清空本地关注及订单数据，及缓存数据
     */
    public void clearContent() {
        hospitalMap = new HashMap<String, String>();
        departmentMap = new HashMap<String, String>();
        doctorMap = new HashMap<String, String>();
        cancelAppFlag = false;
        area_type = -1;
        appPosition = -1;
        confirm_order_success = false;
        changeAttention = false;
        type = -1;
        position = -1;
        attentioin = "";
        orderLocal = false;
        orderOther = false;
        getIDatabase().deleteOutTimeCache();
    }

    public MyApplication() {
        sInstance = this;
    }

    public static synchronized MyApplication getInstance() {
        if (sInstance == null) {
            sInstance = new MyApplication();
        }
        return sInstance;
    }

    private List<Activity> activityList = new LinkedList<Activity>();

    // 添加Activity 到容器中
    public void addActivity(Activity activity) {
        activityList.add(activity);
    }

    // 遍历所有Activity 并finish
    public void exit() {
        for (Activity activity : activityList) {
            activity.finish();
        }
        // System.exit(0);
    }

    /**
     * 上报流量
     */
    private void postLiuliang() {
        if (ConfigUtilHelper.getStime(this) > 0 && ConfigUtilHelper.getEtime(this) > 0) {// 需要有时间段
            if (ConfigUtilHelper.getStime(this) < ConfigUtilHelper.getEtime(this)) {// 结束时间要比开始时间多
                new MyAsynTaskOther(MyApplication.this, GlobalSetting.LIULIANG_TONGJI, initArgMap(), getNetWork()).execute();
            }
        }
    }

    
    
    



    public void onCreate() {
        super.onCreate();
        startLiuliang = ConfigUtilHelper.countCurrentLiuliang(getApplicationContext());

        ImageLoader.getInstance().clearMemoryCache();
        ImageLoader.getInstance().clearDiscCache();
        stime = System.currentTimeMillis() / 1000;
        if (ConfigUtilHelper.isConnectingToInternet(this)) {
            postLiuliang();
            // 检测版本更新
            new GetDataTask().execute();
        }
        initSdcard();
        // GlobalSetting.MOBILE = ConfigUtilHelper.getMobile(this);
        // GlobalSetting.MOBILE = "13684908973";
        // GlobalSetting.MOBILE = "13715218741";
        initHeadInfo();

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext()).threadPoolSize(3).threadPriority(Thread.NORM_PRIORITY - 2).memoryCacheSize(1500000) // 1.5
                                                                                                                                                                                            // Mb
            .denyCacheImageMultipleSizesInMemory().discCacheFileNameGenerator(new Md5FileNameGenerator()).enableLogging() // Not
                                                                                                                          // necessary
                                                                                                                          // in
                                                                                                                          // common
            .build();
        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config);

        // 新的加载图片方式
        mImageCache = new ImageCache();
    }

    /**
     * Image cache, one for all activities and orientations
     */
    private ImageCache mImageCache;

    /**
     * Access to global image cache across Activity instances
     * 
     * @return
     */
    public ImageCache getImageCache() {
        return mImageCache;
    }

    /**
     * 网络类型参数初始化
     * @return
     */
    private JSONObject getNetWork() {
        JSONObject j = new JSONObject();
        float liuliang = ConfigUtilHelper.getLiuliang(this) / 1024 / 1024;
        double f_liuliang = liuliang / 1024;
        try {
            if (ConfigUtilHelper.getNetworkState(this) == ConfigUtilHelper.G2_G3) {
                j.put("2G", f_liuliang);
                j.put("3G", 0);
                j.put("WLAN", 0);
            }
            else {
                j.put("2G", 0);
                j.put("3G", 0);
                j.put("WLAN", f_liuliang);
            }
        }
        catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return j;
    }

    /**
     * 初始化参数
     * @param parameterMap
     * @return
     */
    private Map<String, String> initArgMap() {
        long stime = ConfigUtilHelper.getStime(this);
        long etime = ConfigUtilHelper.getEtime(this);
        TelephonyManager tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
        String imei = tm.getDeviceId();
        String imsi = tm.getSubscriberId();
        String mobile = tm.getLine1Number();
        if (imsi == null) {
            imsi = "";
        }
        if (mobile == null) {
            mobile = "";
        }
        Map<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("appkey", getString(R.string.SZICITY_APPKEY));
        parameterMap.put("ver", ConfigUtilHelper.getVersionName(this));
        parameterMap.put("IMEI", imei);
        parameterMap.put("UDID", "");
        parameterMap.put("IMSI", imsi);
        parameterMap.put("moblie", mobile);
        parameterMap.put("stime", String.valueOf(stime));
        parameterMap.put("etime", String.valueOf(etime));
        return parameterMap;
    }

    private class GetDataTask extends AsyncTask<Void, Void, String[]> {

        // 任务在后台执行
        @Override
        protected String[] doInBackground(Void... params) {
            //String appkey = getString(R.string.SZICITY_APPKEY);
            //String channel = getString(R.string.SZICITY_CHANNEL);
            String appversion = ConfigUtilHelper.getVersionName(MyApplication.this);
            String url = Arguments.CHECK_UPDATE_URL ;
            if (ConfigUtilHelper.debug) {
                Log.i(TAG, "升级url：" + url);
            }
            mUpdateEntity =  ConfigUtilHelper.getUpdateMsg(url, "8",
					"wxcityMobileClient", "2", appversion);
            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            // TODO Auto-generated method stub
            super.onProgressUpdate(values);
      
        }

        @Override
        protected void onPreExecute() {
        
        }

        // 任务执行的结果
        @Override
        protected void onPostExecute(String[] result) {
            /*
             * if(entity.Return.endsWith("1")){
             * showAlertDlg_update(getString(R.string.dialog_update_title),
             * entity.Description, getString(R.string.dialog_update_now),
             * getString(R.string.dialog_update_later)); }
             */
        }
    }

    public IDatabase getIDatabase() {
        return DatabaseImpl.getInstance(this);
    }

    private void initSdcard() {
        GlobalSetting.CACHE_PIC_PATH = getFilesDir().getAbsolutePath() + Arguments.CACHE_PIC_PATH_STR;
        Utils.createMVFolderPrivate();
    }

    public List<Hospital> adHospitals = new ArrayList<Hospital>();
    private String[][] hosData = { { "0", "4612", "广东省深圳市福田莲花路1120号", "5/201010/12870406432977.jpg", "21", "B", "0", "北京大学深圳医院" }, { "0", "2884", "深圳市东门北路3号大院", "5/201010/12867615325922.jpg", "100", "B", "0", "深圳市人民医院" },
        { "0", "7939", "深圳市笋岗西路3002号", "200912/12616319286998.jpg", "22", "B", "0", "深圳市第二人民医院" }, { "0", "0", "深圳市南山区龙珠大道龙苑路16号（桃源村北面）", "5/201105/13062021334499.jpg", "260", "C", "0", "深圳龙珠医院" } };

    /**
     * 初始化首页广告位医院信息
     */
    private void initHeadInfo() {
        for (int i = 0; i < hosData.length; i++) {
            Hospital hos = new Hospital();
            hos.area_type = hosData[i][0];
            hos.left_num = hosData[i][1];
            hos.address = hosData[i][2];
            hos.image = Arguments.image_url + hosData[i][3];
            hos.unit_id = hosData[i][4];
            hos.unit_level = Utils.getHospitalLevelStr(hosData[i][5]);
            hos.is_attention = hosData[i][6];
            hos.unit_name = hosData[i][7];
            adHospitals.add(hos);
        }
    }

    /**
     * 流量统计回调接口函数
     * @param code 0 没有KEY参数 1 接收处理成功 -1 key参数值验证没通过 -2 没有POST[‘data’]参数
     */
    @Override
    public void liuliang_callback(String code) {
        // TODO Auto-generated method stub
        if (code.equals("1")) {// 上报成功清除目前存储流量
            try {
                ConfigUtilHelper.clearLiuliang(getApplicationContext());
            }
            catch (Exception e) {
                // TODO: handle exception
            }
        }
        else {

        }
    }
}
